const App = getApp()
const db = wx.cloud.database()
const _ = db.command
// 监听器
let watcher
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 实践任务详情
    practiceDetails: "",
    modalName: "",
    // 下载回来的文件链接地址
    downloadFilePath: "",
    // 用来分辨是开始时间还是结束时间
    timeKey: "",
    // 用来改变选择时间右边的箭头
    Arrowhead: "",
    // 初始时间
    TimeValue: "",
    // 时间展示
    addtimeValue: "",
    endtimeValue: "",
    // 剩余时间、未开始时间、状态时间
    stateYime: 30 * 60 * 60 * 1000,
    practiceState: "",
    // 编辑更新弹窗
    setshow: false,
    // 按钮loading
    btnloading: false,
    // 显示fab
    fabShow: false,
    // 笼罩层
    overlayShow: false,
    // 详细描述输入框高度
    inputHeight: {
      minHeight: 70
    },
    // 菜单列表
    Menulist: [{
        name: "编辑更新",
        icon: "icon-editor",
        bg: "repeating-linear-gradient(45deg, #00d1FF, #69FF97)",
        path: "",
        bindtap: "setshowPopup",
      }, {
        name: "提前终止",
        icon: "icon-tingzhi",
        bg: "repeating-linear-gradient(45deg, #ED1C24, #FECE12)",
        path: "",
        bindtap: "terminationPractice",
      },
      {
        name: "恢复运行",
        icon: "icon-yunhang",
        bg: " repeating-linear-gradient(45deg, #24FE41, #F7FD47)",
        path: "",
        bindtap: "RestorePractice",
      },
      {
        name: "删除任务",
        icon: "icon-shanchu",
        bg: "repeating-linear-gradient(45deg, #F5317F, #FF7C6E)",
        path: "",
        bindtap: "removePractice",
      },
    ],
    setlist: {
      name: "",
      describe: "",
      addtime: null,
      endtime: null,
      list: []
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    that = this
    let practiceId = JSON.parse(decodeURIComponent(options.passData));
    console.log('传值后', practiceId);
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    that.setData({
      practiceId: practiceId,
      UserInfo: UserInfo
    })
    // 实时数据推送
    App.toast.showLoading('加载中')
    watcher = db.collection('practice')
      .where({
        practiceId: that.data.practiceId
      }).watch({
        onChange: this.onChange.bind(this),
        onError: function (err) {
          console.error(err)
        }
      })
  },

  // 监听器
  onChange(snapshot) {
    App.toast.hideLoading()
    console.log('is init data', snapshot.type === 'init')
    console.log(snapshot);
    if (snapshot.type === 'init') {
      let list = snapshot.docs[0]
      console.log('获取初始化实践详情', list);
      let addtime = App.Time.formatTime(list.addtime)
      let endtime = App.Time.formatTime(list.endtime)
      that.setData({
        practiceDetails: list,
        ['setlist.list']: list.file,
        addtimeValue: addtime,
        endtimeValue: endtime,
      })
      // 获取倒计时
      let stateYime = null
      let practiceState = ""
      if (list.addtime - Date.now() >= 0 && list.practiceSwitch === false) {
        // 如果开始时间距离当前时间大于0，且实践任务没有开始，那就把剩余时间赋值给计时器，为0会自动开启
        stateYime = list.addtime - Date.now()
        practiceState = "尚未开始"
      } else if (list.practiceState === '提前终止') {
        // 如果实践任务状态是"提前终止",那就是人为的提前终止
        stateYime = null
        practiceState = "提前终止"
      } else if (list.addtime - Date.now() < 0 && list.endtime - Date.now() > 0) {
        // 因为实践任务一开始默认是关闭的，如果当前时间已经>开始时间<结束时间那就启动实践任务
        that.addTimeStartPractice()
        stateYime = list.endtime - Date.now()
        practiceState = "正在进行"
      } else {
        // 如果当前时间已经>结束时间，那就终止实践任务
        stateYime = null
        practiceState = "已经终止"
        that.EndTimeClosePractice()
      }
      console.log('stateYime', stateYime);
      console.log('practiceState', practiceState);
      that.setData({
        stateYime: stateYime,
        practiceState: practiceState
      })
    } else {
      let list = snapshot.docs[0]
      console.log('获取更新后实践详情', list);
      if (!list) {
        console.log('没有数据');
        return
      }
      let addtime = App.Time.formatTime(list.addtime)
      let endtime = App.Time.formatTime(list.endtime)
      that.setData({
        practiceDetails: list,
        ['setlist.list']: list.file,
        addtimeValue: addtime,
        endtimeValue: endtime,
      })
      // 获取倒计时
      let stateYime = null
      let practiceState = ""
      if (list.addtime - Date.now() >= 0 && list.practiceSwitch === false) {
        // 如果开始时间距离当前时间大于0，且实践任务没有开始，那就把剩余时间赋值给计时器，为0会自动开启
        stateYime = list.addtime - Date.now()
        practiceState = "尚未开始"
      } else if (list.practiceState === '提前终止') {
        // 如果实践任务状态是"提前终止",那就是人为的提前终止
        stateYime = null
        practiceState = "提前终止"
      } else if (list.addtime - Date.now() < 0 && list.endtime - Date.now() > 0) {
        // 因为实践任务一开始默认是关闭的，如果当前时间已经>开始时间<结束时间那就启动实践任务
        that.addTimeStartPractice()
        stateYime = list.endtime - Date.now()
        practiceState = "正在进行"
      } else {
        // 如果当前时间已经>结束时间，那就终止实践任务
        stateYime = null
        practiceState = "已经终止"
        that.EndTimeClosePractice()
      }
      console.log('stateYime', stateYime);
      console.log('practiceState', practiceState);
      that.setData({
        stateYime: stateYime,
        practiceState: practiceState
      })
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    watcher.close()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 打开编辑更新弹窗
  setshowPopup() {
    // 先更新目前时间
    console.log(App.Time.TimeCode());
    that.setData({
      TimeValue: App.Time.TimeCode(),
    })
    that.setData({
      setshow: true
    });
  },
  // 关闭编辑更新弹窗
  onCloseSet() {
    that.setData({
      setshow: false
    });
  },
  // 关闭提示弹窗
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  // fab
  fabShow() {
    that.setData({
      overlayShow: !that.data.overlayShow,
      fabShow: !that.data.fabShow
    });
  },
  // 关闭fab和笼罩层
  onClickHide() {
    that.setData({
      overlayShow: false,
      fabShow: false
    });
  },

  TimehandleChange(e) {

    // 获取开始时间还是结束时间
    let key = e.currentTarget.dataset.only
    // 获取标准时间
    let Time = e.detail.dateString
    // 将时间转成时间戳
    let formatTime = new Date(Time).getTime()
    if (key == 'add') {
      that.setData({
        addtimeValue: Time,
        'setlist.addtime': formatTime
      });
    } else {
      // 结束时间不能低于开始时间
      if (formatTime <= that.data.setlist.addtime) {
        App.toast.showToast('结束时间不能低于开始时间')
        return false
      }
      that.setData({
        endtimeValue: Time,
        'setlist.endtime': formatTime
      });
    }
    console.log('开始', that.data.setlist.addtime);
    console.log('结束', that.data.setlist.endtime);
  },



  // input
  handleChange(event) {
    console.log(event.detail);
    that.setData({
      [`setlist.${event.currentTarget.id}`]: event.detail
    })
  },

  // 添加附件
  addfile() {
    that.setData({
      btnloading: true
    })
    wx.chooseMessageFile({
      count: 10,
      type: 'all',
      success(res) {
        console.log(res);
        let data = res.tempFiles
        console.log(data);
        const uploadTasks = data.map((file, index) => {
          let cloudPath = "实践任务附件/" + that.data.practiceDetails.courseName + "/" + file.name
          return wx.cloud.uploadFile({
            cloudPath: cloudPath,
            filePath: file.path
          });
        });
        Promise.all(uploadTasks)
          .then(res => {
            let list = []
            res.forEach((item, index) => {
              list.push({
                name: data[index].name,
                size: (data[index].size / 1024 / 1024).toFixed(2),
                id: item.fileID,
                type: data[index].type,
                fileId: Date.now() + index
              })
            })
            let setlist = that.data.setlist.list
            list.forEach(x => {
              setlist.push(x)
            })
            console.log('setlist', setlist);
            that.setData({
              ['setlist.list']: setlist,
              btnloading: false
            })
          })
          .catch(e => {
            that.setData({
              btnloading: false
            })
            console.log(e);
          });
      },
      fail: function (res) {
        that.setData({
          btnloading: false
        })
      }
    })
  },


  // 删除附件
  removefileName(e) {
    const {
      index
    } = e.currentTarget.dataset
    console.log(index);
    let setlist = that.data.setlist.list
    console.log(setlist.splice(index, 1));
    that.setData({
      ['setlist.list']: setlist
    })
  },



  // 下载文件到本地
  downloadFile(e) {
    let fileid = e.currentTarget.dataset.fileid
    App.toast.showLoading('下载中')
    wx.cloud.getTempFileURL({
      fileList: [{
        fileID: fileid,
      }]
    }).then(res => {
      App.toast.hideLoading()
      console.log('返回来的链接', res.fileList[0])
      that.setData({
        modalName: "DialogModal1",
        downloadFilePath: res.fileList[0].tempFileURL,
      })
    }).catch(error => {
      console.error(error)
    })
  },
  // 复制文件链接地址
  codeFilePath(e) {
    console.log(e.currentTarget.dataset);
    let filepath = e.currentTarget.dataset.filepath
    wx.setClipboardData({
      data: filepath,
      success: res => {
        console.log(res);
        App.toast.showToast('地址已经复制', 'none', 1000)
        that.hideModal()
      }
    })
  },
  // 更新详细实践任务
  setPractice(e) {
    App.toast.showLoading('更新中')
    let id = e.currentTarget.dataset.id
    let setlist = that.data.setlist
    console.log('setlist', setlist);
    db.collection('practice').where({
      practiceId: id
    }).update({
      data: {
        name: setlist.name || that.data.practiceDetails.name,
        describe: setlist.describe || that.data.practiceDetails.describe,
        addtime: setlist.addtime || that.data.practiceDetails.addtime,
        endtime: setlist.endtime || that.data.practiceDetails.endtime,
        file: setlist.list
      },
      success: function (res) {
        console.log('更新成功', res.data);
        App.toast.hideLoading()
        that.onCloseSet()
        that.onClickHide()
        that.getPracticeDetails()
      }
    })
  },
  // 预览照片
  previewImage(e) {
    console.log('预览', e.currentTarget.dataset.imgpath);
    let url = e.currentTarget.dataset.imgpath;
    wx.previewImage({
      current: url,
      urls: [url]
    })
  },
  // 恢复运行
  RestorePractice() {
    wx.showModal({
      title: '提示',
      content: '请先在编辑修改合适的开始结束时间，否则会实践任务自动终止',
      confirmText: "我已修改",
      cancelText: "现在去改",
      success(res) {
        if (res.confirm) {
          let practiceDetails = that.data.practiceDetails
          // 判断恢复运行的实践任务的开始时间是否小于当前时间和结束时间是否大于当前时间，只有当前时间在开始后、结束前才可以恢复运行
          if (practiceDetails.addtime - Date.now() < 0 && practiceDetails.endtime - Date.now() > 0) {
            db.collection('practice').where(_.and([{
              practiceId: that.data.practiceDetails.practiceId
            }, {
              'creator.account': _.eq(that.data.UserInfo.account)
            }, ])).update({
              data: {
                practiceSwitch: true,
                practiceState: "恢复运行"
              },
              success: function (res) {
                console.log('已经恢复运行', res);
                that.onClickHide()
                App.toast.showToast('已经恢复运行')
              }
            })

          } else {
            that.onClickHide()
            App.toast.showToast('实践时间不合适', "error")
            return
          }

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 实践任务开始时间已到，应该启动任务
  addTimeStartPractice() {
    if (that.data.practiceDetails.practiceSwitch === true) {
      console.log('实践任务已经开始了');
      return
    }
    db.collection('practice').where({
      practiceId: that.data.practiceDetails.practiceId
    }).update({
      data: {
        practiceSwitch: true,
        practiceState: "正在运行"
      },
      success: function (res) {
        console.log('实践任务已经启动', res);
      }
    })
  },
  // 实践任务结束时间已到，应该终止任务
  EndTimeClosePractice() {
    if (that.data.practiceDetails.practiceSwitch === false) {
      console.log('实践任务已经终止了');
      return
    }
    db.collection('practice').where({
      practiceId: that.data.practiceDetails.practiceId
    }).update({
      data: {
        practiceSwitch: false,
        practiceState: "已经终止"
      },
      success: function (res) {
        console.log('已经终止', res);
        App.toast.showToast('实践任务时间已截止,正在终止实践任务')
      }
    })
  },

  // 提前终止实践任务
  terminationPractice() {
    wx.showModal({
      title: '提示',
      content: '是否提前终止该实践任务',
      success(res) {
        if (res.confirm) {
          // 如果实践任务已经终止了就退出，没必要浪费调用资源
          if (that.data.practiceDetails.practiceSwitch === false) {
            that.onClickHide()
            App.toast.showToast('已经终止了')
            return
          }
          db.collection('practice').where(_.and([{
            practiceId: that.data.practiceDetails.practiceId
          }, {
            'creator.account': _.eq(that.data.UserInfo.account)
          }])).update({
            data: {
              practiceSwitch: false,
              practiceState: "提前终止"
            },
            success: function (res) {
              console.log('已经终止', res);
              that.onClickHide()
              App.toast.showToast('已经终止')
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  // 删除任务
  removePractice() {
    wx.showModal({
      title: '提示',
      content: '是否终止并且删除此实践任务',
      success(res) {
        if (res.confirm) {
          db.collection('practice').doc(that.data.practiceDetails._id).remove({
            success: function (res) {
              console.log('删除成功', res.data)
              App.toast.showToast('删除成功,正在返回')
              setTimeout(() => {
                App.route.relBack('/pages/teachers/list/index')
              }, 1000)
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  // 成员实践任务详情
  memberPractice(e) {
    let data = e.currentTarget.dataset
    console.log('获取点击的同学的学号以及实践任务id', data);
    App.route.navTo('/pages/teachers/practice/memberPractice/index', data)
  }
})